package com.huhao.wshare.Friends;

import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.android.material.imageview.ShapeableImageView;
import com.huhao.wshare.R;

import java.util.ArrayList;
import java.util.List;

public class FriendAdapter extends RecyclerView.Adapter<FriendAdapter.FriendViewHolder> implements Filterable {
    private List<Friend> friendList;
    private List<Friend> friendListFull;

    private final Filter friendFilter = new Filter() {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            List<Friend> filteredList = new ArrayList<>();

            if (constraint == null || constraint.length() == 0) {
                filteredList.addAll(friendListFull);
            } else {
                String filterPattern = constraint.toString().toLowerCase().trim();

                for (Friend friend : friendListFull) {
                    if (friend.getAccount().toLowerCase().contains(filterPattern) ||
                            (friend.getRemark() != null && friend.getRemark().toLowerCase().contains(filterPattern)) ||
                            friend.getUsername().toLowerCase().contains(filterPattern)) {
                        filteredList.add(friend);
                    }
                }
            }

            FilterResults results = new FilterResults();
            results.values = filteredList;
            return results;
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            // 记录旧列表大小
            int oldSize = friendList.size();
            friendList.clear();
            // 修复未检查的赋值和原始类型使用问题
            @SuppressWarnings("unchecked")
            List<Friend> filteredList = (List<Friend>) results.values;
            friendList.addAll(filteredList);
            // 优化数据变更通知，使用更具体的变更事件
            if (oldSize == 0 && friendList.size() > 0) {
                notifyItemRangeInserted(0, friendList.size());
            } else if (oldSize > 0 && friendList.size() == 0) {
                notifyItemRangeRemoved(0, oldSize);
            } else if (oldSize > 0 && friendList.size() > 0) {
                notifyDataSetChanged();
            }
        }
    };

    public FriendAdapter(List<Friend> friendList) {
        this.friendList = friendList;
        this.friendListFull = new ArrayList<>(friendList);
    }

    // 添加更新好友列表的方法
    public void updateFriendList(List<Friend> newFriendList) {
        int oldSize = this.friendList.size();
        this.friendList = newFriendList;
        this.friendListFull = new ArrayList<>(newFriendList);
        if (oldSize == 0 && newFriendList.size() > 0) {
            notifyItemRangeInserted(0, newFriendList.size());
        } else if (oldSize > 0 && newFriendList.size() == 0) {
            notifyItemRangeRemoved(0, oldSize);
        } else if (oldSize > 0 && newFriendList.size() > 0) {
            if (oldSize == newFriendList.size()) {
                notifyItemRangeChanged(0, oldSize);
            } else {
                notifyDataSetChanged();
            }
        }
    }

    @Override
    public Filter getFilter() {
        return friendFilter;
    }

    @NonNull
    @Override
    public FriendViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // 加载单个好友项的布局
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.friend_item, parent, false);
        return new FriendViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull FriendViewHolder holder, int position) {
        Friend friend = friendList.get(position);
        // 判断备注是否为空，不为空显示备注，为空显示用户名
        String displayName = friend.getRemark() != null && !friend.getRemark().isEmpty() ? friend.getRemark() : friend.getUsername();
        holder.tvUsername.setText(displayName);
        holder.tvSigns.setText(friend.getSigns());

        // 根据 gender 字段设置右侧图标
        int drawableResId = 0;
        if ("man".equals(friend.getGender())) {
            drawableResId = R.drawable.ic_male;
        } else if ("woman".equals(friend.getGender())) {
            drawableResId = R.drawable.ic_female;
        }
        if (drawableResId != 0) {
            holder.tvUsername.setCompoundDrawablesWithIntrinsicBounds(
                    null, null,
                    ContextCompat.getDrawable(holder.itemView.getContext(), drawableResId),
                    null
            );
            holder.tvUsername.setCompoundDrawablePadding(8);
        } else {
            holder.tvUsername.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
        }

        // 根据 avatar 和 gender 设置头像
        int defaultAvatarResId;
        if ("man".equals(friend.getGender())) {
            defaultAvatarResId = R.drawable.default_avatar_man;
        } else if ("woman".equals(friend.getGender())) {
            defaultAvatarResId = R.drawable.default_avatar_woman;
        } else {
            defaultAvatarResId = R.drawable.default_avatar_man;
        }

        if (friend.getAvatar() != null) {
            Glide.with(holder.itemView.getContext())
                    .load(friend.getAvatar())
                    .apply(RequestOptions.circleCropTransform())
                    .placeholder(defaultAvatarResId)
                    .error(defaultAvatarResId)
                    .into(holder.ivAvatar);
        } else {
            holder.ivAvatar.setImageResource(defaultAvatarResId);
        }

        // 添加列表项点击事件
        holder.itemView.setOnClickListener(v -> {
            Intent intent = new Intent(holder.itemView.getContext(), FriendActivity.class);
            intent.putExtra("friendId", friend.getId());
            intent.putExtra("remark", friend.getRemark());
            holder.itemView.getContext().startActivity(intent);
        });
    }

    @Override
    public int getItemCount() {
        return friendList.size();
    }

    public static class FriendViewHolder extends RecyclerView.ViewHolder {
        TextView tvUsername;
        TextView tvSigns;
        ShapeableImageView ivAvatar;

        public FriendViewHolder(@NonNull View itemView) {
            super(itemView);
            // 初始化视图组件
            tvUsername = itemView.findViewById(R.id.tv_username);
            tvSigns = itemView.findViewById(R.id.tv_signs);
            ivAvatar = itemView.findViewById(R.id.iv_avatar);
        }
    }
}
